import React, { PureComponent } from 'react';
import { Modal, Form, Input, Select } from 'antd';
import { setLocalStorage } from '../../utils/local_storage';

const FormItem = Form.Item;
const { Option } = Select;
const { TextArea } = Input;

@Form.create()
class SetTmpMsgModal extends PureComponent {
  state = {
    keywords: false,
    chineseStrs: [],
    tmpType: '请选择模板',
  };

  handleOk = e => {
    e.preventDefault();
    const { accountId, form, onOk, templateList } = this.props;
    const { chineseStrs } = this.state;
    // 保存模板消息操作
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { templateTitleId, content, url } = values;
        const { template_id, title } = templateList[templateTitleId];
        const tmpd = {
          template_id: template_id,
          title: title,
          data: content,
          url: url ? url : '',
          chineseStrs: chineseStrs,
        };
        const tmp = JSON.stringify(tmpd);
        // 将tmp内容保存至localStorage
        setLocalStorage(accountId, tmp);
        onOk();
        form.resetFields();
        this.setState({
          tmpType: '请选择模板',
        });
      }
    });
  };

  handleCancel = () => {
    this.props.form.resetFields();
    this.props.onCancel();
    this.setState({
      tmpType: '请选择模板',
    });
  };

  // 处理配置模板选择变化
  handleTmpSelecthChange = v => {
    if (v !== '请选择模板') {
      const { templateList } = this.props;
      const tmpContent = templateList[v].content;
      // 提取keywords
      const keywordsData = tmpContent.match(/{{(\S*)}}/g);
      const keywords = [];
      keywordsData.map(keyword => keywords.push(keyword.replace('{{', '').replace('.DATA}}', '')));
      const chineseStrs = tmpContent.match(/[\u4e00-\u9fa5]{1,10}/g);
      // 设置模板modal所需表单项
      this.setState({
        tmpType: v,
        keywords: keywords,
        chineseStrs: chineseStrs ? chineseStrs : [],
      });
    } else {
      this.setState({
        tmpType: v,
        keywords: false,
      });
    }
  };

  render() {
    const { keywords, chineseStrs, tmpType } = this.state;
    const formitemLabel = ['内容描述', ...chineseStrs, '其他备注'];
    const { visible, appid, form, templateList } = this.props;
    const { getFieldDecorator } = form;
    const titles = [];
    for (const i in templateList) {
      titles.push(templateList[i].title);
    }

    return (
      <Modal
        title="配置模板"
        visible={visible}
        style={{ top: 200 }}
        closable={false}
        cancelText="取消"
        okText="保存"
        width={600}
        onOk={this.handleOk}
        onCancel={this.handleCancel}
      >
        <Form layout="inline">
          <FormItem label="所属Appid">{appid}</FormItem>
          <br />
          <FormItem label="模板名称">
            {getFieldDecorator('templateTitleId', {
              initialValue: '请选择模板',
              rules: [{ type: 'number', message: '请选择模板' }],
            })(
              <Select onChange={this.handleTmpSelecthChange}>
                <Option value="请选择模板">请选择模板</Option>
                {titles.map((value, key) => (
                  <Option key={key} value={key}>
                    {value}
                  </Option>
                ))}
              </Select>
            )}
          </FormItem>
          {keywords && !isNaN(tmpType) ? (
            <div>
              {keywords.map((keyword, index) => (
                <div key={index} style={{ marginBottom: 10 }}>
                  <FormItem label={formitemLabel[index]}>
                    {getFieldDecorator('content.' + keyword + '.text', {
                      rules: [{ required: true, message: '请填写内容' }],
                    })(<Input style={{ width: 300 }} />)}
                  </FormItem>
                  <FormItem label="颜色">
                    {getFieldDecorator('content.' + keyword + '.color', {
                      initialValue:
                        keyword == 'first' || keyword == 'remark' ? '#ff0000' : '#0000ff',
                    })(<Input type="color" style={{ width: 80 }} />)}
                  </FormItem>
                </div>
              ))}
              <FormItem label="跳转链接">
                {getFieldDecorator('url')(<TextArea style={{ width: 400 }} rows={3} />)}
              </FormItem>
            </div>
          ) : (
            <div style={{ color: 'orange' }}>
              请先选择模板,若没有请在公众号内添加模板后,再来填写
            </div>
          )}
        </Form>
      </Modal>
    );
  }
}

export default SetTmpMsgModal;
